import json
import os
from typing import Dict, List, Optional
from database_connection import DatabaseConfig, DatabaseType


class ConfigManager:
    """数据库配置管理器"""

    def __init__(self, config_file: str = "db_configs.json"):
        """
        初始化配置管理器

        Args:
            config_file: 配置文件路径
        """
        self.config_file = config_file
        self.configs: Dict[str, dict] = {}
        self.load_configs()

    def load_configs(self):
        """从文件加载配置"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    self.configs = json.load(f)
            else:
                self.configs = {}
        except Exception as e:
            print(f"加载配置文件失败: {e}")
            self.configs = {}

    def save_configs(self):
        """保存配置到文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.configs, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存配置文件失败: {e}")
            return False

    def save_config(self, name: str, config: DatabaseConfig, overwrite: bool = False) -> bool:
        """
        保存数据库配置

        Args:
            name: 配置名称
            config: 数据库配置对象
            overwrite: 是否覆盖已存在的配置

        Returns:
            bool: 保存是否成功
        """
        if name in self.configs and not overwrite:
            return False

        # 将DatabaseConfig对象转换为字典
        config_dict = {
            'db_type': config.db_type.value,
            'host': config.host,
            'port': config.port,
            'database': config.database,
            'username': config.username,
            'password': config.password  # 注意：实际应用中应该加密存储密码
        }

        self.configs[name] = config_dict
        return self.save_configs()

    def get_config(self, name: str) -> Optional[DatabaseConfig]:
        """
        获取指定名称的配置

        Args:
            name: 配置名称

        Returns:
            DatabaseConfig: 数据库配置对象，如果不存在则返回None
        """
        if name not in self.configs:
            return None

        config_dict = self.configs[name]
        try:
            return DatabaseConfig(
                db_type=DatabaseType(config_dict['db_type']),
                host=config_dict.get('host'),
                port=config_dict.get('port'),
                database=config_dict.get('database'),
                username=config_dict.get('username'),
                password=config_dict.get('password')
            )
        except Exception as e:
            print(f"解析配置失败: {e}")
            return None

    def get_config_names(self) -> List[str]:
        """获取所有配置名称列表"""
        return list(self.configs.keys())

    def delete_config(self, name: str) -> bool:
        """
        删除指定配置

        Args:
            name: 配置名称

        Returns:
            bool: 删除是否成功
        """
        if name in self.configs:
            del self.configs[name]
            return self.save_configs()
        return False

    def config_exists(self, name: str) -> bool:
        """检查配置是否存在"""
        return name in self.configs

    def get_config_info(self, name: str) -> Optional[str]:
        """
        获取配置的简要信息

        Args:
            name: 配置名称

        Returns:
            str: 配置信息字符串
        """
        if name not in self.configs:
            return None

        config = self.configs[name]
        db_type = config['db_type']

        if db_type == 'sqlite':
            return f"SQLite: {config.get('database', 'N/A')}"
        else:
            host = config.get('host', 'localhost')
            port = config.get('port', '')
            database = config.get('database', '')
            username = config.get('username', '')

            if port:
                return f"{db_type.upper()}: {username}@{host}:{port}/{database}"
            else:
                return f"{db_type.upper()}: {username}@{host}/{database}"


# 测试代码
if __name__ == "__main__":
    # 创建配置管理器
    config_manager = ConfigManager("test_configs.json")

    # 测试SQLite配置
    sqlite_config = DatabaseConfig(
        db_type=DatabaseType.SQLITE,
        database="test.db"
    )

    # 测试MySQL配置
    mysql_config = DatabaseConfig(
        db_type=DatabaseType.MYSQL,
        host="localhost",
        port=3306,
        database="testdb",
        username="root",
        password="password"
    )

    # 保存配置
    print("保存SQLite配置:", config_manager.save_config("本地SQLite", sqlite_config))
    print("保存MySQL配置:", config_manager.save_config("本地MySQL", mysql_config))

    # 获取配置列表
    print("配置列表:", config_manager.get_config_names())

    # 获取配置信息
    for name in config_manager.get_config_names():
        print(f"{name}: {config_manager.get_config_info(name)}")

    # 加载配置
    loaded_config = config_manager.get_config("本地SQLite")
    if loaded_config:
        print(f"加载的SQLite配置: {loaded_config.database}")

    print("配置管理器测试完成！")
